package com.test.platform.websocket;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.NonNull;

@Component
public class WebSocketHandler extends TextWebSocketHandler {
    private static final Logger logger = LoggerFactory.getLogger(WebSocketHandler.class);
    private final WebSocketService webSocketService;

    public WebSocketHandler(WebSocketService webSocketService) {
        this.webSocketService = webSocketService;
    }

    @Override
    public void afterConnectionEstablished(@NonNull WebSocketSession session) {
        webSocketService.addSession(session.getId(), session);
    }

    @Override
    public void afterConnectionClosed(@NonNull WebSocketSession session, @NonNull CloseStatus status) {
        webSocketService.removeSession(session.getId());
    }

    @Override
    protected void handleTextMessage(@NonNull WebSocketSession session, @NonNull TextMessage message) {
        try {
            // 处理来自客户端的确认消息
            String payload = message.getPayload();
            if (payload.contains("\"type\":\"confirmation\"")) {
                boolean confirmed = payload.contains("\"result\":true");
                webSocketService.handleConfirmation(confirmed);
            }
        } catch (Exception e) {
            logger.error("处理消息失败: {}", e.getMessage());
        }
    }
}